<?php
namespace control;
// 销售业绩统计
class salesPerformanceStatisticsClass extends adIndexClass
{
    private const page = 'salesPerformanceStatistics';
    private array $list = ['board'=>'数据看板','performance_goals'=>'业绩目标完成情况','payment'=>'计划回款与实际回款','contract_money'=>'商机金额与合同金额','kpi_analysis'=>'关键指标分析',
        'losing_analysis'=>'输单原因分析','sign_ranking'=>'签单排行榜','goal_achievement'=>'目标达成榜'];
    private const title = '销售业绩统计';
    /*返回网页*/
    public function home()
    {
        $root = root;
        // 搜索文本框
        $searchTxt = self::searchText(array('name' => 'staffName', 'click' => "cardSearch()", 'title' => '员工', 'search' => true)) .
            hidden(array('name' => 'stid', 'value' => '')) .
            self::searchText([
                'click' => "cardSearch()",
                'search' => true,
                "name" => "month",
                "title" => L('salesPerformanceStatistics.home.timeSlot'),
                "class" => "line28",
                "value" => date('Y-m'),
                'laydate' => ['type' => 'month']
            ]);
        // 搜索文本框
        $right_searchTxt = self::searchText([
            "name" => "month",
            "title" => L('salesPerformanceStatistics.home.timeSlot'),
            'search' => true,
            "value" => '',
            'click' => "search_line('aimRankForm','salesPerformanceStatistics','aimRank')",
            'laydate' => ['range' => '~', 'type' => 'month']
        ]);
        $signRank_searchTxt = self::searchText([
            "name" => "month",
            "title" => L('salesPerformanceStatistics.home.timeSlot'),
            "search" => true,
            'click' => "search_line('signRankForm','salesPerformanceStatistics','signRank')",
            "value" => '',
            'laydate' => ['range' => '~', 'type' => 'month']
        ]);
        $record = query('user_setting',"stid = '".self::$stid."' and type = '销售业绩统计' and coid = '".self::$coid."'");
        $setting = (array)json_decode($record['value'],true);
        $board = in_array('board',$setting)?'display:block;':'display:none;';
        $performance_goals = in_array('performance_goals',$setting)?'display:block;':'display:none;';
        $payment = in_array('payment',$setting)?'display:block;':'display:none;';
        $contract_money = in_array('contract_money',$setting)?'display:block;':'display:none;';
        $kpi_analysis = in_array('kpi_analysis',$setting)?'display:block;':'display:none;';
        $losing_analysis = in_array('losing_analysis',$setting)?'display:block;':'display:none;';
        $sign_ranking = in_array('sign_ranking',$setting)?'display:block;':'display:none;';
        $goal_achievement = in_array('goal_achievement',$setting)?'display:block;':'display:none;';

        $boardWord = L('salesPerformanceStatistics.home.board');
        $contractMoneyWord = L('salesPerformanceStatistics.home.contractMoney');
        $backMoneyWord = L('salesPerformanceStatistics.home.backMoney');
        $remindMoneyWord = L('salesPerformanceStatistics.home.remindMoney');
        $completeRateWord = L('salesPerformanceStatistics.home.completeRate');
        $myriWord = L('salesPerformanceStatistics.home.myri');
        $signRankWord = L('salesPerformanceStatistics.home.signRank');
        $aimRankWord = L('salesPerformanceStatistics.home.aimRank');
        $loadWord = L('salesPerformanceStatistics.home.load');
        $html = <<<EOT
        <style>
            .title-card-li-content{
              text-align: center;padding-top: 50px
            }
            .title-card-li-money{
              font-size: 28px;font-weight: bold
            }
             .home-warp{flex-direction: column}
             .box-content{flex: 1;display: flex;flex-direction: row;padding: 10px 10px 0 10px;}
             .left-box{width: 71.5%;}
             .right-box{flex: 1}
             .flex-div > .data-widget:nth-child(2n-1){margin-right: 0}
             .home-warp .flex-div-children ul{padding-right: 0}
             .revenue{display: flex;align-items: center;}
             .vertical-line{width: 100%;}
        </style>
        <div class="chart_setting"><img onclick="layer('salesPerformanceStatistics','setting',{})" src="{$root}img/control/menu_two.svg" alt=""></div>
        <div class="home-warp">
         <div class="box-content">
            <div class="left-box">
            <div class="flex-div">
                <div class="flex-div-children data-widget" style="{$board}">
                    <form name="data-card"><div class="frame-title"><span class="title-card">{$boardWord}</span>{$searchTxt}</div></form>
                    <ul class="revenue">
                        <li class="vertical-line">
                            <div class="title-card-li-content" id="contractMoneyHtml">
                               <div>{$contractMoneyWord}</div>
                               <div><span class="title-card-li-money">￥0.00</span><span>{$myriWord}</span></div>
                            </div>
                        </li>
                        <li class="vertical-line">
                            <div class="title-card-li-content" id="backMoneyHtml">
                               <div>{$backMoneyWord}</div>
                               <div><span class="title-card-li-money">￥0.00</span><span>{$myriWord}</span></div>
                            </div>
                        </li>
                        <li class="vertical-line">
                             <div class="title-card-li-content" id="remindMoneyHtml">
                               <div>{$remindMoneyWord}</div>
                               <div><span class="title-card-li-money">￥0.00</span><span>{$myriWord}</span></div>
                            </div>
                        </li>
                        <li class="vertical-line">
                         <div class="title-card-li-content" id="completeRateHtml">
                               <div>{$completeRateWord}</div>
                               <div><span class="title-card-li-money">0%</span><span></span></div>
                            </div>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="flex-div">
                <div class="flex-div-children data-widget" style="{$performance_goals}">
                    {$this->dataBoard(['title' => L('salesPerformanceStatistics.home.targetAim'), 'fun' => 'targetAim', 'startDate' => date('Y-m', strtotime("-12 month")), 'endDate' => date('Y-m')])}
                </div>
                 </div>
  <div class="flex-div">
                <div class="flex-div-children data-widget" style="{$payment}">
                    {$this->dataBoard(['title' => L('salesPerformanceStatistics.home.planAndFact'), 'fun' => 'planAndFact', 'startDate' => date('Y-m', strtotime("-12 month")), 'endDate' => date('Y-m')])}
                </div>
           <div class="flex-div-children colum-line"></div>
                <div class="flex-div-children data-widget" style="{$contract_money}">
                    {$this->dataBoard(['title' => L('salesPerformanceStatistics.home.contractAndOpportunity'), 'fun' => 'contractAndOpportunity', 'startDate' => date('Y-m', strtotime("-12 month")), 'endDate' => date('Y-m')])}
                </div>
                 </div>
                  <div class="flex-div">
                 <div class="flex-div-children data-widget" style="{$kpi_analysis}">
                    {$this->dataBoard(['title' => L('salesPerformanceStatistics.home.kpiData'), 'fun' => 'kpiData'])}
                </div>
                <div class="flex-div-children colum-line"></div>
                <div class="flex-div-children data-widget" style="{$losing_analysis}">
                    {$this->dataBoard(['title' => L('salesPerformanceStatistics.home.loseAnalysis'), 'fun' => 'loseAnalysis'])}
                </div>
                 </div>
            </div>
            <div class="right-box">
              <div class="data-widget m-b-10" style="{$sign_ranking}">
                   <form name="signRankForm"> <p><span class="title-card">{$signRankWord}</span>{$signRank_searchTxt}</p></form>
                   <div id="signRankHtml"></div>
                </div>
                <div class="data-widget" style="{$goal_achievement}">
                   <form name="aimRankForm"><p><span class="title-card">{$aimRankWord}</span>{$right_searchTxt}</p></form>
                   <div id="aimRankHtml"></div>
                </div>
            </div>
            </div>
        </div>
    </div>
     <script src='{$this->root}static/javascript/echarts.min.js'></script>
<script>
function search_line(formName,cla,fun) {
     $("#" + fun + "Html").html("{$loadWord}");
    $.post(root + "control/adIndex.html?cla=" + cla + "&fun=" + fun, $("[name='" + formName + "']").serialize(), function (data) {
         $("#" + fun + "Html").html(data.html);
    }, "json");
}


/**
* 看板搜索
*/
function cardSearch(){
      ['contractMoney', 'backMoney', 'remindMoney', 'completeRate'].forEach((fun)=>{
                    search_line('data-card','salesPerformanceStatistics', fun)
    })
}

$(function() {
    ['contractMoney', 'backMoney', 'remindMoney', 'completeRate'].forEach((fun)=>{
                    search_line('data-card','salesPerformanceStatistics', fun)
    });
    search_line('aimRankForm','salesPerformanceStatistics','aimRank');
    search_line('signRankForm','salesPerformanceStatistics','signRank')
    $("[name='staffName']").each(function (){
          $(this).bigAutocomplete({
            url:root + 'control/adIndex.html?cla=component&fun=getStaff',
            callback:function(data,e){
                console.log(data.id);
                e.parent().siblings("input[name='stid']").val(data.id)
        }})  
    })
})


</script>
EOT;
        $style = '<style>
        .left-box, .right-box{margin: 0;}
        .left-box .flex-div, .right-box .flex-div{margin: 0 10px 10px 0;}
        .flex-div>.data-widget:nth-child(2n-1){margin-right: 0;}
        .m-b-10{margin-bottom: 10px;}
        .right-box-ul{
            height: 500px;
            max-height: none;
         }
         .right-box-title{
            display: flex;
         }
         .right-text{
            height: auto;
         }
         .right-box-title li{
            float: left;margin: 5px 10px;min-width: 70px;text-align: center;
         }
         .data-widget-select{
            margin-right: 10px;
         }
         .data-widget-select .fs-label{
             height: 15px;line-height: 15px;
         }
         .data-widget-select .fs-label-wrap{
             border-radius: 4px;
         }
         .aim-rank li{
            margin: 5px 0;
         }
         .aim-rank .right-box-title li:nth-child(1){min-width: 40px}
         .aim-rank .right-box-title li:nth-child(2){min-width: 50px}
         .aim-rank .right-box-title li:nth-child(3){min-width: 100px}
         .aim-rank .right-box-title li:nth-child(4){min-width: 100px}
</style>';
        return head("ad") . $style . $this->adheader($this->getOnion()) . $html . warn() . $this->adfooter();
    }

    /**
     * 显示设置
     * @return bool|string
     */
    public function setting()
    {
        $list = $this->list;
        $li = '';
        $index = 0;
        $setting = query('user_setting',"type='销售业绩统计' and stid = '".self::$stid."' and coid = '".self::$coid."'");
        $setText =(array)json_decode($setting['value'],true);
        foreach ($list as $id=>$name){
            $index++;
            $checked = '';
            if (in_array($id,$setText)){
                $checked = 'checked';
            }
            $name = L('salesPerformanceStatistics.list.'.$id);
            $li.=<<<eof
 <li><div class="li-content"><span class="left">{$name}</span><div class="switch">
                  <input id="cmn-toggle-{$index}" name='setting[]' value='{$id}' $checked class="cmn-toggle cmn-toggle-round" type="checkbox">
                  <label for="cmn-toggle-{$index}"></label>
            </div></div></li>
eof;
           }
        $saveWord = L('salesProcessStatistics.setting.save');
            //生成表单
            $html = <<<efo
<form name="settingForm">
<div class="setting-content">
    <ul>
       {$li}
    </ul>
   
</div>
<div style="width: 100%;text-align: center"><button class="button" onclick="subForm('settingForm',root+'control/adIndex.html?cla=salesPerformanceStatistics&fun=settingEdit')">{$saveWord}</button></div>
</form>
<style>
.li-content{height: 30px;line-height: 30px}
.setting-content>ul{margin: 25px}
.setting-content>ul>li{width: 100%;border-bottom: 1px solid #F2F2F2;padding: 8px 0;}
.switch{display: inline-block;vertical-align: bottom;float: right}
</style>
efo;

        //返回弹出层
        return $this->layer(array("title" => L('salesProcessStatistics.setting.settingChart'), "height" => 550, "width" => 400, "html" => $html));
    }

    /**
     * 图标展示设置
     * @return bool|string
     */
    public function settingEdit(): bool|string
    {
        $setting = $this->post('setting')?:[];
        $record = query('user_setting',"type='销售业绩统计' and stid = '".self::$stid."' and coid = '".self::$coid."'");
        if (!empty($record['id'])){
            $json['warn'] = static::update(array(
                'table'=>'user_setting',
                'field'=>[
                    'value'=>json_encode($setting,320)
                ],
                'where'=>"id = '$record[id]'"
            ));
        }else{
            $json['warn'] = static::insert(array(
                'table'=>'user_setting',
                'field'=>[
                    'coid'=>self::$coid,
                    'stid'=>self::$stid,
                    'type'=>'销售业绩统计',
                    'value'=>json_encode($setting,320)
                ],
            ));
        }
        if (in_array($json['warn'],['新增成功','更新成功'])){
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }
    /**
     * 目标达成榜
     */
    public function aimRank(): bool|string
    {
        $month = $this->post('month');
        $where = $aimWhere = " and coid = '".self::$coid."'";
        if (!empty($month)) {
            $where .= " and date_format(time,'%Y-%m') ='$month'";
            $aimWhere .= " and month ='$month'";
        }
        //数据查询
        $sql = find(array("table" => "staff", "field" => "stid,(select ifnull(sum(money),0) from sales_contract where state='已通过' and salesman = staff.stid {$where}) as contractMoney,(select ifnull(sum(money),0) from performance_target where  staffId like concat('%',staff.stid,'%') {$aimWhere}) as aimMoney,
        if((select ifnull(sum(money),0) from performance_target where  staffId like concat('%',staff.stid,'%') {$aimWhere})>0,
        ((select ifnull(sum(money),0) from sales_contract where state='已通过' and salesman = staff.stid {$where})/(select ifnull(sum(money),0) from performance_target where staffId like concat('%',staff.stid,'%') {$aimWhere})*100),0) as rate", "where" => " order by rate desc limit 10"));
        $ul = '<ul class="right-box-ul aim-rank">';
        if (!$sql['array']) {
            $ul .= '<li class="nodata">'.L('salesPerformanceStatistics.aimRank.none').'</li>';
        } else {
            $ul .= "<li><ul class='right-box-title'><li>".L('salesPerformanceStatistics.aimRank.ranking')."</li><li>".L('salesPerformanceStatistics.aimRank.stid')."</li><li>".L('salesPerformanceStatistics.aimRank.contractMoney')."</li><li>".L('salesPerformanceStatistics.aimRank.aimMoney')."</li><li>".L('salesPerformanceStatistics.aimRank.rate')."</li></ul></li>";

            foreach ($sql['array'] as $index => $array) {
                $array['rate'] = round($array['rate'], 2);
                $array['aimMoney'] =round($array['aimMoney']?:0,2);
                $array['contractMoney'] = round($array['contractMoney']?:0,2);
                $ul .= "<li><ul class='right-box-title'><li>" . ($index + 1) . "</li><li>" . (self::findStaff($array['stid'])) . "</li><li>{$array['contractMoney']}</li><li>{$array['aimMoney']}</li><li>{$array['rate']}%</li></ul></li>";
            }
        }
        $ul .= '</ul>';
        // 拼接字符串
        $json['html'] = $ul;
        return json_encode($json, 320);
    }

    /**
     * 签单排行榜
     */
    public function signRank(): string
    {
        $month = $this->post('month');
        $where = " and coid = '".self::$coid."'";
        $default = '';
        if (!empty($month)) {
            $timeArr = explode(' ~ ', $month);
            $where .= " and date_format(time,'%Y-%m') >='$timeArr[0]' and date_format(time,'%Y-%m') <= '$timeArr[1]'";
            $default = $timeArr[0] . ' ~ ' . $timeArr[1];
        }

        $table = "(select salesman,sum(any_value(money)) as money from sales_contract where state='已通过' {$where} group by salesman) as a";
        //数据查询
        $sql = find(array("table" => $table, "where" => " order by money desc limit 10"));
        $ul = '<ul class="right-box-ul">';
        if (!$sql['array']) {
            $ul .= '<li class="nodata">'.L('salesPerformanceStatistics.aimRank.none').'</li>';
        } else {
            $ul .= "<li><ul class='right-box-title'><li>".L('salesPerformanceStatistics.aimRank.ranking')."</li><li>".L('salesPerformanceStatistics.aimRank.stid')."</li><li>".L('salesPerformanceStatistics.aimRank.contractMoney')."</li><li>".L('salesPerformanceStatistics.aimRank.rate')."</li></ul></li>";
            foreach ($sql['array'] as $index => $array) {
                $money = find(array('table' => 'payment', 'sum' => 'money', "where" => " and targetId in (select id from sales_contract where state = '已通过' {$where})"));
                $array['money'] = round($array['money'],2);
                $rate = $array['money'] > 0 ? round($money / $array['money'], 3) * 100 : '-';
                $ul .= "<li><ul class='right-box-title'><li>" . ($index + 1) . "</li><li>" . (self::findStaff($array['salesman'])) . "</li><li>{$array['money']}</li><li>{$rate}%</li></ul></li>";
            }
        }
        $ul .= '</ul>';
        // 拼接字符串
        $json['html'] = $ul;
        return json_encode($json, 320);
    }

    /**
     * 输单原因分析 - 返回数据
     */
    public function loseAnalysis(): bool|string
    {
        $month = $this->post('where');
        $where = " and coid = '".self::$coid."'";
        if (!empty($month)) {
            $timeArr = explode(' ~ ', $month);
            $where .= " and date(time) >='$timeArr[0]' and date(time) <= '$timeArr[1]'";
        }
        if ($this->post('stid')) {
            $where .= " and manager = '" . $this->post('stid') . "'";
        }
        $series = [];
        $clientSource = explode('，', para('lostOpportunityOption'));
        foreach ($clientSource as $source) {
            $num = static::total(array('table' => 'opportunity', "where" => " and reason !='' and reason = '$source' {$where}"));
            $series[] = ['name' => $source, 'data' => $num];
        }
        $data = [
            "series" => $series
        ];
        $json['html'] = $this->pie($data);
        return json_encode($json, 320);
    }

    /**
     * 关键指标分布
     */
    public function kpiData(): bool|string
    {
        $month = $this->post('month');
        $clueWhere = $opportunityWhere = $clientWhere = $contractWhere  = " and coid = '".self::$coid."'";
        $contractDetailWhere = " and main.coid='".self::$coid."'";
        if (!empty($month)) {
            $timeArr = explode(' ~ ', $month);
            $clueWhere .= " and date_format(time,'%Y-%m') >='$timeArr[0]' and date_format(time,'%Y-%m') <='$timeArr[1]'";
            $opportunityWhere .= " and date_format(time,'%Y-%m') >='$timeArr[0]' and date_format(time,'%Y-%m') <='$timeArr[1]'";
            $clientWhere .= " and date_format(time,'%Y-%m') >='$timeArr[0]' and date_format(time,'%Y-%m') <='$timeArr[1]'";
            $contractWhere .= " and date_format(signedDate,'%Y-%m') >='$timeArr[0]' and date_format(signedDate,'%Y-%m') <='$timeArr[1]'";
            $contractDetailWhere .= " and date_format(main.signedDate,'%Y-%m') >='$timeArr[0]' and date_format(main.signedDate,'%Y-%m') <='$timeArr[1]'";
        }

        $yData = [];
        if ($this->post('stid')) {
            $clueWhere .= " and manager = '" . $this->post('stid') . "'";
            $opportunityWhere .= " and manager = '" . $this->post('stid') . "'";
            $clientWhere .= " and manager = '" . $this->post('stid') . "'";
            $contractWhere .= " and salesman = '" . $this->post('stid') . "'";
            $contractDetailWhere .= " and main.salesman = '" . $this->post('stid') . "'";
        }
        //线索转化率
        $clueTotal = static::total(array('table' => "clue", "where" => $clueWhere));
        $clueToClientTotal = static::total(array('table' => "clue", "where" => "isClient = 1 {$clueWhere} "));
        $yData[0] = $clueTotal > 0 ? round(($clueToClientTotal / $clueTotal) * 100) : 0;
        //商机挖掘率
        $opportunityTotal = static::total(array('table' => "opportunity", "where" => $opportunityWhere));
        $clientTotal = static::total(array('table' => "kehu", "where" => $clientWhere));
        $yData[1] = $clientTotal > 0 ? round(($opportunityTotal / $clientTotal) * 100) : 0;
        //商机转换率
        $opportunityTotal = static::total(array('table' => "opportunity", "where" => $opportunityWhere));
        //$contractTotal = static::total(array('table' => "sales_contract", "where" => "{$contractWhere} "));
        $contractTotal = find(array('table' => 'sales_contract_detail as mx join sales_contract as main on main.id = mx.orderId','single' => " 1=1 and mx.sourceId in (select id from quotations where opId <> '') ".$contractDetailWhere." group by mx.orderId ", 'field' => "IFNULL(count(mx.orderId),0) as num "));
        $contractTotal['num']=$contractTotal['num']??0;
        $yData[2] = $opportunityTotal > 0 ? round(($contractTotal['num'] / $opportunityTotal) * 100) : 0;
        //回款率
        $contractMoney = find(array('table' => 'sales_contract', 'where' => $contractWhere, 'sum' => "money"));
        $paymentMoney = find(array('table' => 'payment', 'where' => "targetId in (select id from sales_contract where 1=1 {$contractWhere})", 'sum' => "money"));
        $yData[3] = $contractMoney > 0 ? round(($paymentMoney / $contractMoney) * 100) : 0;
        //复购率
        $first_contract = static::total(array('table' => "sales_contract", "where" => "isFirst = 1 {$contractWhere}"));
        $total_contract = static::total(array('table' => "sales_contract", "where" => $contractWhere));
        $yData[4] = $total_contract > 0 ? round((1 - ($first_contract / $total_contract)) * 100) : 0;
        $data = [
            "xData" => [
                [
                    'name' => L('salesPerformanceStatistics.kpiData.clueToClientRate'),
                    'max' => 100
                ],
                [
                    'name' => L('salesPerformanceStatistics.kpiData.opportunityRate'),
                    'max' => 100
                ],
                [
                    'name' => L('salesPerformanceStatistics.kpiData.opportunityConversion'),
                    'max' => 100
                ],
                [
                    'name' => L('salesPerformanceStatistics.kpiData.paymentRate'),
                    'max' => 100
                ],
                [
                    'name' => L('salesPerformanceStatistics.kpiData.repurchaseRate'),
                    'max' => 100
                ],
            ],
            "yData" => [
                'name' => '',
                'data' => $yData
            ]
        ];
        $json['html'] = $this->radarChart($data);
        return json_encode($json, 320);
    }

    /**
     * 雷达图
     */
    public function radarChart($data)
    {
        $indicator = json_encode($data['xData'], 320);
        $series = json_encode($data['yData']['data'], 320);
        $option = <<<EOT
        var option = {

  radar: {
    // shape: 'circle',
    indicator: {$indicator}
  },
  series: [
    {
      name: '',
      type: 'radar',
      data: [
        {
          value: {$series},
          name: '{$data['yData']['name']}',
          areaStyle:{},
        },

      ]
    }
  ]
};
EOT;
        //返回
        return $this->echarts($option);
    }

    /**
     * 商机金额与合同金额
     * @return bool|string
     */
    public function contractAndOpportunity(): bool|string
    {
        $month = $this->post('month');
        if (!empty($month)) {
            $timeArr = explode(' ~ ', $month);
        } else {
            $timeArr[0] = $this->date;
            $timeArr[1] = date('Y-m-d', strtotime("-12 month"));
        }
        $xData = [];
        $yData = [];
        $dataArr = self::dateRange($timeArr[0], $timeArr[1]);
        $where = $aimWhere = " and coid = '".self::$coid."'";
        if ($this->post('stid')) {
            $where .= " and salesman = '" . $this->post('stid') . "'";
            $aimWhere .= " and manager = '" . $this->post('stid') . "'";
        }
        foreach ($dataArr as $index => $month) {
            $xData[] = date('Y.m', strtotime($month));
            //商机金额
            $opportunity = find(array('table' => 'opportunity', 'single' => "date_format(exSignDate,'%Y-%m') ='$month' {$aimWhere}", 'field' => "ifnull(sum(exSaleMoney),0) as money"))['money'];
            $yData[0][] = $opportunity;
            //合同金额
            $contractMoney = find(array('table' => 'sales_contract', 'where' => "date_format(signedDate,'%Y-%m') = '$month' {$where}", 'sum' => "money"));
            $yData[1][] = $contractMoney;

        }
        $data = [
            "name" => $xData,
            "series" => [
                [
                    'name' => L('salesPerformanceStatistics.contractAndOpportunity.opportunity'),
                    'data' => $yData[0]
                ],
                [
                    'name' => L('salesPerformanceStatistics.contractAndOpportunity.contract'),
                    'data' => $yData[1]
                ]
            ]
        ];
        $json['html'] = $this->curve($data, 'area');
        return json_encode($json, 320);
    }

    /**
     * 计划回款与实际回款 数据
     */
    public function planAndFact(): bool|string
    {
        $month = $this->post('month');
        if (!empty($month)) {
            $timeArr = explode(' ~ ', $month);
        } else {
            $timeArr[0] = $this->date;
            $timeArr[1] = date('Y-m-d', strtotime("-12 month"));
        }
        $xData = [];
        $yData = [];
        $dataArr = self::dateRange($timeArr[0], $timeArr[1]);
        $aimWhere = " and coid = '".self::$coid."'";
        $where =  " and a.coid = '".self::$coid."'";
        if ($this->post('stid')) {
            $where .= " and salesman = '" . $this->post('stid') . "'";
            $aimWhere .= " and managerId = '" . $this->post('stid') . "'";
        }
        foreach ($dataArr as $index => $month) {
            $xData[] = date('Y.m', strtotime($month));
            //计划回款金额
            $planMoney = find(array('table' => 'sales_contract_payback as a join sales_contract as b on a.orderId = b.id', 'single' => "b.state = '已通过' and date_format(a.date,'%Y-%m') ='$month' {$where}", 'field' => "ifnull(sum(a.money),0) as money"))['money'];
            $yData[0][] = $planMoney;
            //实际回款
            $factMoney = find(array('table' => 'payment', 'where' => "date_format(recordDate,'%Y-%m') = '$month' {$aimWhere}", 'sum' => "money"));
            $yData[1][] = $factMoney;

        }
        $data = [
            "name" => $xData,
            "series" => [
                [
                    'name' => L('salesPerformanceStatistics.planAndFact.planBack'),
                    'data' => $yData[0]
                ],
                [
                    'name' => L('salesPerformanceStatistics.planAndFact.factBack'),
                    'data' => $yData[1]
                ]
            ]
        ];
        $json['html'] = $this->curve($data);
        return json_encode($json, 320);
    }

    /**
     * 业绩目标完成情况 - 返回数据
     *
     */
    public function targetAim(): bool|string
    {
        $month = $this->post('month');
        if (!empty($month)) {
            $timeArr = explode(' ~ ', $month);
        } else {
            $timeArr[0] = $this->date;
            $timeArr[1] = date('Y-m-d', strtotime("-12 month"));
        }
        $where = $aimWhere = " and coid = '".self::$coid."'";
        if ($this->post('stid')) {
            $where .= " and salesman = '" . $this->post('stid') . "'";
            $aimWhere .= " and staffId like '%" . $this->post('stid') . "%'";
        }
        $xData = [];
        $yData = [];
        $dataArr = self::dateRange($timeArr[0], $timeArr[1]);
        foreach ($dataArr as $index => $month) {
            $xData[] = date('Y.m', strtotime($month));
            //合同金额
            $contractMoney = find(array('table' => 'sales_contract', 'where' => "state = '已通过' and date_format(signedDate,'%Y-%m') ='$month' {$where}", 'sum' => "money"));
            $yData[1][] = $contractMoney?:0;
            //目标
            $aim = find(array('table' => 'performance_target', 'where' => "month = '$month' {$aimWhere}", 'sum' => "money"));
            $yData[0][] = $aim?:0;

        }
        $data = [
            "name" => $xData,
            "series" => [
                [
                    'name' => L('salesPerformanceStatistics.targetAim.target'),
                    'data' => $yData[0]
                ],
                [
                    'name' => L('salesPerformanceStatistics.targetAim.contractMoney'),
                    'data' => $yData[1]
                ],
            ]
        ];
        $json['html'] = $this->barCharts($data);
        return json_encode($json, 320);
    }

    /**
     * 回款金额
     */
    public function backMoney(): bool|string
    {

        $stid = $this->post('stid');
        $month = $this->post('month');
        $where = " and coid = '".self::$coid."'";
        if ($stid) {
            $where .= " and managerId = '$stid'";
        }
        if ($month) {
            $where .= " and date_format(recordDate,'%Y-%m') ='$month'";
        }
        $money = find(array('table' => 'payment', 'where' => "classify = 2 and targetId !='' and moneyType = '合同款'" . $where, 'sum' => "money"));
        $text = $money > 10000 ? '万' : '';
        $money = $money > 10000 ? round(($money / 10000), 2) : round($money, 2);
        $json['html'] = <<<efo
         <div title="收款登记中关联了销售合同的合同款类型的收款金额">回款金额</div>
         <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
efo;
        return json_encode($json, 320);
    }

    /**
     * 剩余应收金额
     */
    public function remindMoney(): bool|string
    {

        $stid = $this->post('stid');
        $month = $this->post('month');
        $where =" and coid = '".self::$coid."'";
        if ($stid) {
            $where .= " and salesman = '$stid'";
        }
        if ($month) {
            $where .= " and date_format(signedDate,'%Y-%m') ='$month'";
        }
        //合同金额
        $contractMoney = find(array('table' => 'sales_contract', 'where' => "state = '已通过'" . $where, 'sum' => "money"));

        $backWhere = '';
        if ($stid) {
            $backWhere .= " and managerId = '$stid'";
        }
        if ($month) {
            $backWhere .= " and date_format(recordDate,'%Y-%m') ='$month'";
        }
        $backMoney = find(array('table' => 'payment', 'where' => "classify = 2 and targetId in (select id from sales_contract where state = '已通过' {$where}) and moneyType = '合同款'" . $backWhere, 'sum' => "money"));
        $money = $contractMoney - $backMoney;
        $text = $money > 10000 ? '万' : '';
        $money = round($money > 10000 ? ($money / 10000) : $money, 2);
        $amountReceivableWord = L('salesPerformanceStatistics.remindMoney.amountReceivable');
        $json['html'] = <<<efo
         <div title="合同金额-回款金额">{$amountReceivableWord}</div>
         <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
efo;
        return json_encode($json, 320);
    }

    /**
     * 合同金额
     */
    public function contractMoney(): bool|string
    {
        $stid = $this->post('stid');
        $month = $this->post('month');
        $where =" and coid = '".self::$coid."'";
        if ($stid) {
            $where .= " and salesman = '$stid'";
        }
        if ($month) {
            $where .= " and date_format(signedDate,'%Y-%m') ='$month'";
        }
        $money = find(array('table' => 'sales_contract', 'where' => "state = '已通过'" . $where, 'sum' => "money"));
        $text = $money > 10000 ? '万' : '';
        $money = round($money > 10000 ? ($money / 10000) : $money, 2);
        $contractMoneyWord = L('salesPerformanceStatistics.aimRank.contractMoney');
        $json['html'] = <<<efo
         <div title="签约日期在搜索月份的已通过销售合同金额">{$contractMoneyWord}</div>
         <div><span class="title-card-li-money">￥{$money}</span><span>{$text}</span></div>
efo;
        return json_encode($json, 320);
    }

    /**
     * 目标完成率
     */
    public function completeRate(): bool|string
    {
        $stid = $this->post('stid');
        $month = $this->post('month');
        $where = $aimWhere = " and coid = '".self::$coid."'";
        if ($stid) {
            $where .= " and salesman = '$stid'";
            $aimWhere .= " and staffId like '%$stid%'";
        }
        if ($month) {
            $where .= " and date_format(signedDate,'%Y-%m') ='$month'";
            $aimWhere .= " and month = '$month'";
        }
        $money = find(array('table' => 'sales_contract', 'where' => "state = '已通过'" . $where, 'sum' => "money"));
        $aim = find(array('table' => 'performance_target', 'where' => $aimWhere, 'sum' => "money"));
        $rate = $aim > 0 ? round($money / $aim, 3) * 100 : '-';
        $completeRateWord = L('salesPerformanceStatistics.completeRate.completeRate');
        $json['html'] = <<<efo
         <div title="签约日期在搜索月份的已通过销售合同金额/搜索月份的业绩目标">{$completeRateWord}</div>
         <div><span class="title-card-li-money">{$rate}%</span><span></span></div>
efo;
        return json_encode($json, 320);
    }


    /**
     * 数据看板
     *
     * @param array $data 格式 [ 'title'=>'标题', 'fun'=>'数据源函数', 'condition'=> '显示查询条件，为空表示显示' ]
     */
    public static function dataBoard(array $data): string
    {
        $endMoon = date("Y-m");
        $startMoon = date("Y-m", strtotime('-1 month'));
        if (isset($data['startDate'])) {
            $startMoon = $data['startDate'];
        }
        if (isset($data['endDate'])) {
            $endMoon = $data['endDate'];
        }
        $staffSelect = self::searchText(array('name' => 'stName','search'=>true,'click' => "search_line('{$data['fun']}Form','salesPerformanceStatistics','{$data['fun']}')", 'id'=>suiji(), 'title' => '员工')) . hidden(array('name' => 'stid', 'value' => ''));

        $html = '';
        if (!isset($data['condition']) || $data['condition'] !== false) {
            $searchTxt = self::searchText([
                'click' => "search_line('{$data['fun']}Form','salesPerformanceStatistics','{$data['fun']}')",
                'search' => true,
                "name" => "month",
                "title" => L('salesPerformanceStatistics.home.timeSlot'),
                "class" => "line28",
                "value"   => $startMoon . ' ~ ' . $endMoon,
                'laydate' => ['range' => '~', 'type' => 'month',]
            ]);
            $html .= "
                    <form name='{$data['fun']}Form'>" .
                "<div class='frame-title'><span class=\"title-card\">{$data['title']}</span>".$staffSelect. ""
                . $searchTxt
                ."</div></form>
                ";
        }
        $html .= "
		<div id='{$data['fun']}Html' class='data-box-show'>".L('salesPerformanceStatistics.home.load')."</div>
		<script>
        $(function(){
            search_line('{$data['fun']}Form','salesPerformanceStatistics','{$data['fun']}')
             $('[name=stName]').each(function (){
                  $(this).bigAutocomplete({
                    url:root + 'control/adIndex.html?cla=component&fun=getStaff',
                    callback:function(data,e){
                        e.parent().siblings('input[name=stid]').val(data.id)
                }})  
            })
        });</script>";
        //返回
        return $html;
    }
}
